// 听筒 接收探测广播，或者多播单播

use crate::core::{MessageType,DiscoveryFrame};
use log::info;
use tokio::net::UdpSocket;

pub async fn broadcast_listener() -> tokio::io::Result<()> {
    let address = crate::CONFIG.get().unwrap().address.clone();
    let socket = UdpSocket::bind(format!(
        "{}:{}",
        address.this_network_ip, address.listen_port
    ))
    .await?;
    socket.set_broadcast(true)?; // 启用广播
    let mut buf = [0; 1024];
    loop {
        let (len, addr) = socket.recv_from(&mut buf).await?;
        if let Some(frame) = DiscoveryFrame::decode(&buf[..len]) {
            match frame.msg_type {
                MessageType::Heartbeat => {
                    info!("发现主机: {}@{}", frame.hostname, addr);
                    // 回复 Ack
                    let ack_frame = DiscoveryFrame::build_ack_frame();
                    socket.send_to(&ack_frame.encode(), addr).await?;
                }
                MessageType::Query => { /* 立即回复心跳 */ }
                _ => {}
            }
        }
    }
}

pub async fn send_heartbeat(socket: &UdpSocket) {
    let address = crate::CONFIG.get().unwrap().address.clone();
    let frame = DiscoveryFrame::build_heartbeat_frame([0; 16], "miniLanDrop".to_string(), 0);
    socket
        .send_to(
            &frame.encode(),
            format!("{}:{}", address.broadcast_ip, address.listen_port),
        )
        .await
        .unwrap();
}

